using System;
using Quiki.Helpers;

namespace Quiki.Querying
{
    public class QueryParser : IQueryParser
    {
        public Query Parse(string queryText)
        {
            IQuerySpecification spec = null;

            foreach (string split in queryText.SplitIntoWords())
            {
                string trimmed = split.Trim();
                if (trimmed.Length == 0)
                    continue;

                WikiDocReference specRef = new WikiDocReference(trimmed);
                if (false == specRef.IsCategory)
                    throw new ArgumentException("Only categories are allowed in the query", "queryText");

                IQuerySpecification currentSpec = new CategoryQuerySpecification(specRef.Parts[1]);

                if (spec == null)
                    spec = currentSpec;
                else if (spec is CategoryQuerySpecification)
                {
                    AndQuerySpecification andSpec = new AndQuerySpecification();
                    andSpec.AddComponentSpec(spec);
                    andSpec.AddComponentSpec(currentSpec);
                    spec = andSpec;
                }
                else
                {
                    ((AndQuerySpecification)spec).AddComponentSpec(currentSpec);
                }
            }

            return new Query(spec);
        }
    }
}